package com.woniu.log;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class Ip {
    /**
     * 为了获取 HttpServletRequest
     * @return
     */
    public static HttpServletRequest getRequest(){
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
    /**
     * 获取ip地址
     * @return
     */
    public static String getIpAddress(){
        HttpServletRequest request=getRequest();
        String ip = request.getHeader("x-forwarded-for");
        System.out.println("**********************"+ip+"++++++++++++++++++++");
        if (ip==null|| ip.length()==0||"unknown".equalsIgnoreCase(ip)){
            ip=request.getHeader("Proxy-Client-IP");
        }if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            •获取客户端ip，直接使用ip = request.getRemoteAddr ()，虽然获取到的可能是代理的ip不是客户端的ip，但这个获取到的ip基本上是不可能伪造的
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
